﻿using System;
using System.Linq;
using ggHD.Domain.Repisitories;
using LinqToDB.Mapping;
using OpenPop.Mime;

namespace ggHD.Domain.BizObj
{
    [Table(Schema = "dbo", Name = "RawMails")]
    public partial class RawMail : IEntity<long>
    {
        public RawMail()
        {
        }

        public static RawMail CreateFromMessage(Message msg,string msgUid)
        {
            return new RawMail()
            {
                RawData = msg.RawMessage,
                DateLoaded = DateTime.Now,
                DateSent = msg.Headers.DateSent,
                FromAddress = msg.Headers.From.Address,
                FromName = msg.Headers.From.DisplayName,
                MailAccount = string.Join(";", msg.Headers.To.Select(a => a.Address).ToArray()),
                MsgSubject = msg.Headers.Subject,
                MsgUid = msgUid,
                MsgId = string.IsNullOrWhiteSpace(msg.Headers.MessageId) ? msg.Headers.DateSent + " " + msg.Headers.From.Address : msg.Headers.MessageId
            };
        }

        [PrimaryKey, Identity]
        public long Id { get; set; } // bigint
        [Column, Nullable]
        public string MsgId { get; set; } // nvarchar(256)
        [Column, NotNull]
        public string MsgUid { get; set; } // nvarchar(256)
        [Column, Nullable]
        public string MsgSubject { get; set; } // nvarchar(256)
        [Column, Nullable]
        public string FromAddress { get; set; } // nvarchar(256)
        [Column, Nullable]
        public string FromName { get; set; } // nvarchar(256)
        [Column, Nullable]
        public string MailAccount { get; set; } // nvarchar(256)
        [Column, Nullable]
        public DateTime? DateSent { get; set; } // datetime
        [Column, Nullable]
        public DateTime? DateLoaded { get; set; } // datetime
        [Column, NotNull]
        public byte[] RawData { get; set; } // varbinary(-1)

        [Column("Id"), Identity]
        public long Key { get; set; }

        public Message AsMessage
        {
            get { return new Message(RawData); }
        }
    }
}
